/*
 * ===================================================================
 *  TS 26.104
 *  REL-5 V5.4.0 2004-03
 *  REL-6 V6.1.0 2004-03
 *  3GPP AMR Floating-point Speech Codec
 * ===================================================================
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include "interf_dec.h"
#include "sp_dec.h"
#include "typedef.h"

#include <string.h>
#define AMR_MAGIC_NUMBER "#!AMR\n"


int main (int argc, char * argv[]) {

    FILE * file_speech, *file_analysis;

    int frames = 0;
    int * destate;
    int read_size;
    unsigned char analysis[32];
    short synth[160];
    enum Mode dec_mode;
    char magic[8];
    short block_size[16]={ 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0 };


    /* Process command line options */
    if (argc == 3) {

        file_speech = fopen(argv[2], "wb");
        if (file_speech == NULL) {
            fprintf ( stderr, "%s%s%s\n","Use: ",argv[0], " input.file output.file " );
            return 1;
        }

        file_analysis = fopen(argv[1], "rb");
        if (file_analysis == NULL) {
            fprintf ( stderr, "%s%s%s\n","Use: ",argv[0], " input.file output.file " );
            fclose(file_speech);
            return 1;
        }

    }
    else {
        fprintf ( stderr, "%s%s%s\n","Use: ",argv[0], " input.file output.file " );
        return 1;
    }

    /*--------------------------------------------------------------------------------------------------------------*/

    /* init decoder */
    destate = Decoder_Interface_init();
    /* read and verify magic number */
    fread( magic, sizeof( char ), strlen( AMR_MAGIC_NUMBER ), file_analysis );
    if ( strncmp( magic, AMR_MAGIC_NUMBER, strlen( AMR_MAGIC_NUMBER ) ) ) {
        fprintf( stderr, "%s%s\n", "Invalid magic number: ", magic );
        fclose( file_speech );
        fclose( file_analysis );
        return 1;
    }

    /* find mode, read file */
    while (fread(analysis, sizeof (unsigned char), 1, file_analysis ) > 0)
    {

        dec_mode = (analysis[0] >> 3) & 0x000F;

        read_size = block_size[dec_mode];

        fread(&analysis[1], sizeof (char), read_size, file_analysis );

        frames ++;

        /* call decoder */
        Decoder_Interface_Decode(destate, analysis, synth, 0);

        fwrite( synth, sizeof (short), 160, file_speech );
    }

    Decoder_Interface_exit(destate);

    fclose(file_speech);
    fclose(file_analysis);
    fprintf ( stderr, "\n%s%i%s\n","Decoded ", frames, " frames.");

    return 0;
}
